import os
import sys

def convert_size(size_bytes):
    """将字节大小转换为易读格式（KB/MB/GB）"""
    if size_bytes == 0:
        return "0B"
    units = ("B", "KB", "MB", "GB")
    i = 0
    while size_bytes >= 1024 and i < len(units) - 1:
        size_bytes /= 1024
        i += 1
    return f"{size_bytes:.2f}{units[i]}"

def get_folder_size(folder_path):
    """计算文件夹总大小（包括所有子文件夹和文件）"""
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(folder_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            try:
                total_size += os.path.getsize(fp)
            except OSError:
                continue  # 跳过无法访问的文件
    return total_size

def main():
    # 获取目标文件夹路径
    # if len(sys.argv) > 1:
    #     target_folder = sys.argv[1]
    # else:
    #     print("请指定文件夹路径")
    #     return
    target_folder = "C:\\Users\\gedin\\AppData\\Roaming"
    target_folder = os.path.normpath(target_folder)
    if not os.path.isdir(target_folder):
        print(f"错误：'{target_folder}' 不是有效文件夹")
        return

    # 收集所有子文件夹及其大小
    folder_sizes = []
    for entry in os.listdir(target_folder):
        full_path = os.path.join(target_folder, entry)
        if os.path.isdir(full_path):
            try:
                size = get_folder_size(full_path)
                folder_sizes.append((entry, size))
            except Exception as e:
                print(f"计算 '{entry}' 大小时出错: {str(e)}")

    # 按大小降序排序
    folder_sizes.sort(key=lambda x: x[1], reverse=True)

    # 打印结果
    print(f"\n{'子文件夹名称':<40}{'大小':>15}")
    print("-" * 55)
    for name, size in folder_sizes:
        print(f"{name:<40}{convert_size(size):>15}")

if __name__ == "__main__":
    main()